import { isArray, isObject, isEmpty } from '../../baseUtil.js';

const defMessages = function (type, obj = {}) {
	const label = obj.label;
	const msgs = {
		type: `${label}值类型需为${obj?.rule?.type}`,
		required: `${label}不能为空`,
		maxLength: `${label}长度不能大于${obj?.rule?.maxLength}`,
		minLength: `${label}长度不能小于${obj?.rule?.minLength}`
	}
	
	return msgs[type] || '校验失败';
}

module.exports = function (obj = {}) {
	const { prop, value, rules, label } = obj;
	if(!rules) return { result: true };
	
	if(isArray(rules)) {
		for(let i = 0; i < rules.length; i++) {
			const item = rules[i];
			if(isObject(item)) {
				const res = validate({...obj, rule: item});
				if(!res.result) return {...res, ...obj};
			}else{
				console.log('rule需为Object类型');
				console.warn('rule需为Object类型');
			}
		}
	}
	else{
		const res = validate({...obj, rule: rules});
		if(!res.result) return {...res, ...obj};
	}
	return { result: true }
}

function validate(obj = {}) {
	const {rule} = obj;
	let res = { result: true };
	
	if(!isEmpty(rule.type)) {
		if(!type(obj)) {
			res.result = false;
			res.errType = 'type';
			res.message = rule.message || defMessages('type', obj);
			return res;
		}
	}
	
	if(!isEmpty(rule.required)) {
		if(!required(obj)) {
			res.result = false;
			res.errType = 'required';
			res.message = rule.message || defMessages('required', obj);
			return res;
		}
	}
	
	if(!isEmpty(rule.maxLength)) {
		if(!maxLength(obj)) {
			res.result = false;
			res.errType = 'maxLength';
			res.message = rule.message || defMessages('maxLength', obj);
			return res;
		}
	}
	
	if(!isEmpty(rule.minLength)) {
		if(!minLength(obj)) {
			res.result = false;
			res.errType = 'minLength';
			res.message = rule.message || defMessages('minLength', obj);
			return res;
		}
	}
	
	return res;
}

function type(obj = {}) {
	const { value, rule } = obj;
	const type = rule.type;
	switch(type) {
		case 'array':
			return isArray(value);
			break;
		case 'object':
			return isObject(value);
			break;
		default:
			return typeof value == type;
			break;
	}
}

function required(obj = {}) {
	const { value } = obj;
	if(isArray(value)) {
		return value.length !== 0;
	}
	return !isEmpty(value);
}

function maxLength(obj = {}) {
	const {value, rule} = obj;
	if(typeof value == 'string' || isArray(value)) {
		return value.length <= Number(rule.maxLength);
	}
	return true;
}

function minLength(obj = {}) {
	const {value, rule} = obj;
	if(typeof value == 'string' || isArray(value)) {
		return value.length >= Number(rule.minLength);
	}
	return true;
}